package middlewares

import (
	"io/ioutil"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

type ReqBodyConfig struct {
	Skipper middleware.Skipper
}

func ReqBodyWithConfig(config ReqBodyConfig) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			urlPath := c.Path()
			switch urlPath {
			case "/api/user/file",
				"/api/uploader",
				"/webapi/user/file",
				"/api/order/notify/forcePay",
				"/webapi/order/notify/forcePay":
				return next(c)
			}

			//Body内容过大情况下用buf读取更优，ReadAll会一直阻塞直到读完
			//buf := new(bytes.Buffer)
			//io.Copy(buf, c.Request().Body)
			//bodyStr := buf.String()

			body, _ := ioutil.ReadAll(c.Request().Body)
			bodyStr := string(body)
			if len(bodyStr) == 0 {
				bodyStr = "{}"
			}
			if bodyStr[:1] == "=" { //ios特別寫
				bodyStr = bodyStr[1:]
			}
			c.Set("body", bodyStr)
			return next(c)
		}
	}
}
